package com.vancouver.knows.ui.fragment.my;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.pangu.AMApplication;
import com.pangu.bean.PageInfo;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullRecyclerViewItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchUserBusinessImagesTaskMark;
import com.vancouver.knows.util.AppUtils;

import java.util.Set;
import java.util.TreeSet;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Chris Li on 2016-08-24.
 */
public class UserImageGalleryRecyclerView extends PullRecyclerViewItemBrowser<AMApplication> {

    private Context mContext;
    private BusinessModule bModule;
    private ImageGalleryListener mListener;

    private UserImageGalleryAdapter mAdapter;

    public UserImageGalleryRecyclerView(Context context, ARefreshViewController mController) {
        super(context, mController);
        this.mContext = context;
        this.bModule = ((MainApplication) imContext).getBusinessModule();

        if (context instanceof ImageGalleryListener) {
            mListener = (ImageGalleryListener) context;
        }
    }

    @Override
    protected RecyclerView.LayoutManager createLayoutManager() {
        return new GridLayoutManager(mContext, 4);
    }

    @Override
    protected RecyclerView.Adapter createAdapter() {
        mAdapter = new UserImageGalleryAdapter(mContext);
        return mAdapter;
    }

    @Override
    protected void setRecyclerViewParameters(RecyclerView recyclerView) {
        recyclerView.setPadding(0, mContext.getResources().getDimensionPixelSize(R.dimen.recycler_view_padding), 0, 0);
        recyclerView.setClipToPadding(false);
    }

    @Override
    protected void handleLoadNewItems(ATaskMark taskMark) {
        FetchUserBusinessImagesTaskMark fetchUserBusinessImagesTaskMark = (FetchUserBusinessImagesTaskMark) taskMark;
        String userId = "";
        UserInfo userInfo = bModule.getCacheManager().getUserInfo();
        if (userInfo != null) {
            userId = userInfo.getUserID();
        }
        bModule.getServiceWrapper().fetchUserBusinessImages(this, fetchUserBusinessImagesTaskMark, userId);
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        super.receiveResult(taskMark, exception, trackerResult);
        if (exception == null) {
            if (taskMark instanceof FetchUserBusinessImagesTaskMark) {
                if (mListener != null) {
                    FetchUserBusinessImagesTaskMark fetchUserBusinessImagesTaskMark = (FetchUserBusinessImagesTaskMark) taskMark;
                    PageInfo pageInfo = fetchUserBusinessImagesTaskMark.getPageInfo();
                    if (pageInfo != null) {
                        mListener.onImagesLoaded(pageInfo.getTotalCount());
                    } else {
                        mListener.onImagesLoaded(0);
                    }
                }
            }
        }
    }

    @Override
    public boolean handleRefreshLoadItem() {
        mAdapter.clearSelected();
        return super.handleRefreshLoadItem();
    }

    public interface ImageGalleryListener {
        void onImageSelected(Set<String> selectedImages);
        void onImagesLoaded(int total);
    }

    public class UserImageGalleryAdapter extends RecyclerView.Adapter<UserImageGalleryAdapter.UserImageViewHolder> {

        private Context mContext;
        private Set<String> mSelectedImages;

        public UserImageGalleryAdapter(Context context) {
            this.mContext = context;
            this.mSelectedImages = new TreeSet<>();
        }

        @Override
        public UserImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            int size = AppUtils.getWindowWidth(parent.getContext()) / 4;
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_user_image_item, parent, false);
            view.setLayoutParams(new RecyclerView.LayoutParams(size, size));
            return new UserImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final UserImageViewHolder holder, int position) {

            FetchUserBusinessImagesTaskMark taskMark = (FetchUserBusinessImagesTaskMark) mTaskMark;
            if (position == getItemCount() - 1 && getItemCount() < taskMark.getPageInfo().getTotalCount()) {
                tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
            }
            final String imgUrl = bModule.getCacheManager().getUserBusinessImages().get(position);
            Picasso.with(holder.itemView.getContext()).load(imgUrl).fit().centerCrop().into(holder.image);
            if (mSelectedImages.contains(imgUrl)) {
                holder.overlay.setVisibility(View.VISIBLE);
            } else {
                holder.overlay.setVisibility(View.GONE);
            }

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mSelectedImages.contains(imgUrl)) {
                        mSelectedImages.remove(imgUrl);
                        holder.overlay.setVisibility(View.GONE);
                    } else {
                        mSelectedImages.add(imgUrl);
                        holder.overlay.setVisibility(View.VISIBLE);
                    }

                    if (mListener != null) {
                        mListener.onImageSelected(mSelectedImages);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return bModule.getCacheManager().getUserBusinessImages().size();
        }

        public void clearSelected() {
            mSelectedImages.clear();
        }

        public class UserImageViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.image)
            ImageView image;
            @Bind(R.id.overlay)
            RelativeLayout overlay;

            public UserImageViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }
}
